package com.demarc.pesquisas.infraestrutura.persistencia.interceptador;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.joda.time.DateTime;

import com.demarc.pesquisas.infraestrutura.persistencia.ObjetoPersistenteVersionado;

public class EntidadeAuditavelInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = -3805070331406417754L;

	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		setAuditableData(entity, currentState, propertyNames, false);
		return true;
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		setAuditableData(entity, state, propertyNames, true);
		return true;
	}

	private void setAuditableData(Object entity, Object[] state,
			String[] propertyNames, boolean insert) {

		if (entity instanceof ObjetoPersistenteVersionado) {
			List<String> propertyNamesList = Arrays.asList(propertyNames);
			String username = "nomeUsuario";
			DateTime now = DateTime.now();

			int indexUpdaterName = propertyNamesList
					.indexOf("usuarioAtualizacao");
			int indexUpdateDate = propertyNamesList
					.indexOf("ultimaAtualizacao");

			if (indexUpdaterName >= 0 && indexUpdateDate >= 0) {
				// FIXME atg substituir por dados reais, após a implementação do
				// login.
				state[indexUpdaterName] = username;
				state[indexUpdateDate] = now;
			}
		}
	}
}
